package com.zmn.plat.business.impl.service.category;

import java.util.Date;
import java.util.Objects;
import java.util.Optional;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.string.InitialUtil;
import com.zmn.plat.business.interfaces.service.category.ItemCategoryBService;
import com.zmn.plat.model.entity.service.category.ItemCategory;
import com.zmn.plat.services.interfaces.service.category.ItemCategoryService;
import com.zmn.plat.services.interfaces.service.item.ServiceItemService;

/**
 * @author tanbiao
 * @description
 * @since 2019/12/5 9:30
 * @modifier
 **/
@Service
public class ItemCategoryBServiceImpl implements ItemCategoryBService {
    @Resource
    private ItemCategoryService faultCategoryService;
    @Resource
    private ServiceItemService faultItemService;

    @Override
    public ItemCategory findByKey(Integer categId) {
        ItemCategory faultCategory = null;
        if (categId == null || categId == 0) {
            faultCategory = new ItemCategory();
        } else {
            faultCategory = Optional.ofNullable(faultCategoryService.findByKey(categId)).orElse(new ItemCategory());
        }
        // 排序默认最大排序加1
        if (faultCategory.getSort() == null) {
            Integer sort = faultCategoryService.findMaxSort();
            sort = sort == null ? 1 : sort + 1;
            faultCategory.setSort(sort);
        }
        return faultCategory;
    }

    @Override
    public Integer addEdit(ItemCategory faultCategory, String mcStaffName) {
        Date now = DateUtil.getNow();
        Integer categId = faultCategory.getCategId();
        String firstLetter = InitialUtil.getFristEnName(faultCategory.getCategName());
        faultCategory.setFirstLetter(firstLetter == null ? "" : firstLetter);
        if (categId == null || categId == 0) {
            faultCategory.setCreater(mcStaffName);
            faultCategory.setCreateTime(now);
            faultCategory.setUpdater(mcStaffName);
            faultCategory.setUpdateTime(now);
            return faultCategoryService.insert(faultCategory);
        } else {
            ItemCategory faultCategoryOld = faultCategoryService.findByKey(faultCategory.getCategId());
            faultCategory.setUpdater(mcStaffName);
            faultCategory.setUpdateTime(now);
            // 修改故障项目的故障名称
            if (!Objects.equals(faultCategoryOld.getCategName(), faultCategory.getCategName())) {
                faultItemService.updateCategNameByCategId(faultCategory.getCategName(), faultCategory.getCategId());
            }

            return faultCategoryService.updateByKey(faultCategory);
        }
    }
}
